package com.example.mvcdemo.controller;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Li_yizYa
 * Date: 2025/7/3
 * Time: 10:18
 */
@RestController
@RequestMapping("/header")
public class HeaderController {
    // 获取 cookie
    @RequestMapping("/getCookie")
    public String getCookie(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null || cookies.length == 0) {
            return "获取 cookie 失败";
        }
        for (Cookie cookie : cookies) {
            System.out.println(cookie.getName() + ": " + cookie.getValue());
        }
        return "获取 cookie 成功";
    }

    @RequestMapping("/getCookie2")
    public String getCookie2(@CookieValue("test2") String test) {
        return "从 Cookie 中获取信息，test: " + test;
    }

    @RequestMapping("/setSession")
    public String setSession(HttpServletRequest request) {
        // 获取 session 对象
        HttpSession session = request.getSession();
        session.setAttribute("userName", "张三");
        session.setAttribute("age", 15);

        return "设置 session 成功";
    }

    // 获取 session 方式1
    @RequestMapping("/getSession")
    public String getSession(HttpServletRequest request) {
        HttpSession session = request.getSession();
        // session 类似 map 的结构
        String userName = (String)session.getAttribute("userName");
        Integer age = (Integer)session.getAttribute("age");
        return "从 session 中获取信息，userName: " + userName + ", age: " + age;
    }

    // 获取 session 方式2
    @RequestMapping("/getSession2")
    public String getSession2(HttpSession session) {
        // session 类似 map 的结构
        String userName = (String)session.getAttribute("userName");
        Integer age = (Integer)session.getAttribute("age");
        return "从 session 中获取信息，userName: " + userName + ", age: " + age;
    }

    // 获取 session 方式3
    @RequestMapping("/getSession3")
    public String getSession3(@SessionAttribute("userName") String userName) {
        return "从 session3 中获取信息, userName: " + userName;
    }

    @RequestMapping("/getHeader")
    public String getHeader(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        return "userAgent: " + userAgent;
    }

    @RequestMapping("/getHeader2")
    public String getHeader2(@RequestHeader("User-Agent") String userAgent) {
        return "userAgent: " + userAgent;
    }

}
